﻿using System;
using System.Linq;
using System.Reflection;

namespace Nomad.WebSync.Service.DAO {
    [Serializable]
    public partial class Task {
        public void Copy(Task instance) {
            PropertyInfo[] properties = this.GetType().GetProperties();
            foreach (var property in properties) {
                if (property.CanRead && property.CanWrite) {
                    var propertyValue = property.GetValue(instance, null);
                    property.SetValue(this, propertyValue, null);
                }
            }
        }

        public Task Clone() {
            var result = new Task();
            PropertyInfo[] properties = this.GetType().GetProperties();
            foreach (var property in properties) {
                if (property.CanRead && property.CanWrite) {
                    var propertyValue = property.GetValue(this, null);
                    property.SetValue(result, propertyValue, null);
                }
            }
            return result;
        }

        public void Synchronize(string username) {
            using (var context = new WebSyncDataContext()) {
                this.State = (byte)States.Synchronized;
                this.Account = context.Accounts.SingleOrDefault(query => query.Username == username);

                var item = context.Tasks.SingleOrDefault(query => query.ID == this.ID);
                if (item != null)
                    item.Copy(this);
                else
                    context.Tasks.InsertOnSubmit(this);
                context.SubmitChanges();
            }
        }

        public void Remove() {
            using (var context = new WebSyncDataContext()) {
                var item = context.Tasks.SingleOrDefault(query => query.ID == this.ID);
                if (context != null) {
                    context.Tasks.DeleteOnSubmit(item);
                    context.SubmitChanges();
                }
            }
        }

        public static Task[] ListByAccount(string username) {
            using (var context = new WebSyncDataContext()) {
                var query = from item in context.Tasks
                            where item.Account.Username == username
                            select item;

                return query.ToArray();
            }
        }
    }
}
